<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>登录</title>
    <!-- 添加公共文件引用 -->
    <script src="assets/js/state.js"></script>
    <script src="assets/js/api.js"></script>
    <script src="assets/js/loading.js"></script>
    <style>
        /* 添加更新对话框样式 */
        .update-dialog {
            display: none;
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background: white;
            padding: 24px;
            border-radius: 12px;
            box-shadow: 0 4px 24px rgba(0, 0, 0, 0.15);
            z-index: 1001;
            width: 90%;
            max-width: 400px;
        }

        .update-dialog.show {
            display: block;
        }

        .update-dialog h3 {
            margin-bottom: 16px;
            font-size: 18px;
            color: #2d3436;
        }

        .update-info {
            margin-bottom: 20px;
            font-size: 14px;
            line-height: 1.6;
            color: #4a5568;
            max-height: 200px;
            overflow-y: auto;
        }

        .update-actions {
            display: flex;
            gap: 12px;
            justify-content: flex-end;
        }

        .update-button {
            padding: 8px 16px;
            border: none;
            border-radius: 6px;
            font-size: 14px;
            cursor: pointer;
            transition: all 0.3s ease;
        }

        .update-now {
            background: #4776E6;
            color: white;
        }

        .update-later {
            background: #e2e8f0;
            color: #4a5568;
        }

        .update-button:hover {
            transform: translateY(-1px);
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
        }

        .dialog-overlay {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.5);
            z-index: 1000;
        }

        .dialog-overlay.show {
            display: block;
        }

        .dialog-overlay.force-update {
            background: rgba(0, 0, 0, 0.75);
            backdrop-filter: blur(4px);
        }

        .update-dialog.force-update {
            background: linear-gradient(to bottom, #ffffff, #f8f9fa);
            border: 1px solid rgba(0, 0, 0, 0.1);
        }

        .update-notice {
            display: flex;
            align-items: center;
            gap: 8px;
            padding: 12px;
            background: rgba(239, 68, 68, 0.1);
            border-radius: 8px;
            margin-bottom: 20px;
            color: #ef4444;
        }

        .update-notice i {
            font-size: 18px;
        }

        .update-dialog.force-update .update-button {
            width: 100%;
            padding: 12px;
            background: #4776E6;
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
            font-size: 16px;
        }

        .update-dialog.force-update .update-button:hover {
            background: #3461c1;
        }

        .update-dialog.force-update .update-info {
            background: rgba(71, 118, 230, 0.05);
            padding: 16px;
            border-radius: 8px;
            margin: 16px 0;
        }

        /* 添加消息提示样式 */
        .message-box {
            position: fixed;
            top: 20px;
            left: 50%;
            transform: translateX(-50%);
            padding: 12px 24px;
            border-radius: 8px;
            color: white;
            font-size: 14px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
            z-index: 1000;
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .message-success {
            background-color: #10b981;
        }

        .message-error {
            background-color: #ef4444;
        }

        .message-info {
            background-color: #3b82f6;
        }

        .loading-spinner {
            display: inline-block;
            width: 16px;
            height: 16px;
            border: 2px solid rgba(255, 255, 255, 0.3);
            border-radius: 50%;
            border-top-color: #fff;
            animation: spin 1s ease-in-out infinite;
        }

        @keyframes spin {
            to {
                transform: rotate(360deg);
            }
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            background: #ffffff;
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            padding-top: 48px; /* 为公告栏留出空间 */
        }

        .login-container {
            width: 100%;
            max-width: 900px;
            padding: 24px;
        }

        .login-card {
            display: flex;
            background: white;
            border-radius: 16px;
            box-shadow: 0 4px 24px rgba(0, 0, 0, 0.08);
            overflow: hidden;
            transition: all 0.3s ease;
        }

        .login-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 28px rgba(0, 0, 0, 0.12);
        }

        .login-image {
            flex: 1;
            background: linear-gradient(135deg, #4776E6 0%, #8E54E9 100%);
            padding: 40px;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            color: white;
            text-align: center;
        }

        .login-image img {
            width: 100%;
            max-width: 320px;
            margin-bottom: 24px;
        }

        .login-image h2 {
            font-size: 28px;
            margin-bottom: 16px;
        }

        .login-image p {
            font-size: 16px;
            opacity: 0.9;
            line-height: 1.6;
        }

        .login-content {
            flex: 1;
            min-width: 420px;
        }

        .login-header {
            background: linear-gradient(135deg, #4776E6 0%, #8E54E9 100%);
            padding: 32px 24px;
            text-align: center;
            color: white;
        }

        .login-header h1 {
            font-size: 24px;
            font-weight: 600;
            margin-bottom: 8px;
        }

        .login-header p {
            font-size: 14px;
            opacity: 0.9;
        }

        .login-form {
            padding: 32px 24px;
        }

        .form-group {
            margin-bottom: 24px;
        }

        .form-label {
            display: block;
            font-size: 14px;
            font-weight: 500;
            color: #2d3436;
            margin-bottom: 8px;
        }

        .form-input {
            width: 100%;
            padding: 12px 16px;
            border: 1px solid #e1e4e8;
            border-radius: 8px;
            font-size: 15px;
            color: #2d3436;
            transition: all 0.3s ease;
            background: #f8f9fa;
        }

        .form-input:focus {
            outline: none;
            border-color: #4776E6;
            background: white;
            box-shadow: 0 0 0 3px rgba(71, 118, 230, 0.1);
            transform: translateY(-1px);
        }

        .form-footer {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 24px;
        }

        .remember-me {
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .remember-me input[type="checkbox"] {
            width: 16px;
            height: 16px;
            border-radius: 4px;
        }

        .forgot-password {
            color: #4776E6;
            text-decoration: none;
            font-size: 14px;
        }

        .login-button {
            width: 100%;
            padding: 12px;
            background: linear-gradient(135deg, #4776E6 0%, #8E54E9 100%);
            border: none;
            border-radius: 8px;
            color: white;
            font-size: 16px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.3s ease;
            position: relative;
            overflow: hidden;
        }

        .login-button:hover {
            transform: translateY(-1px);
            box-shadow: 0 4px 12px rgba(71, 118, 230, 0.2);
        }

        .login-button::after {
            content: '';
            position: absolute;
            top: 50%;
            left: 50%;
            width: 0;
            height: 0;
            background: rgba(255, 255, 255, 0.2);
            border-radius: 50%;
            transform: translate(-50%, -50%);
            transition: width 0.3s, height 0.3s;
        }

        .login-button:hover::after {
            width: 300px;
            height: 300px;
        }

        .login-divider {
            margin: 24px 0;
            display: flex;
            align-items: center;
            color: #a0a7b0;
        }

        .login-divider::before,
        .login-divider::after {
            content: "";
            flex: 1;
            height: 1px;
            background: #e1e4e8;
        }

        .login-divider span {
            padding: 0 16px;
            font-size: 14px;
        }

        .social-login {
            display: flex;
            gap: 12px;
        }

        .social-button {
            flex: 1;
            padding: 12px;
            border: 1px solid #e1e4e8;
            border-radius: 8px;
            background: white;
            color: #2d3436;
            font-size: 14px;
            cursor: pointer;
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
        }

        .social-button:hover {
            background: #f8f9fa;
            border-color: #d0d3d9;
        }

        .register-link {
            text-align: center;
            padding: 24px;
            border-top: 1px solid #e1e4e8;
            color: #636e72;
            font-size: 14px;
        }

        .register-link a {
            color: #4776E6;
            text-decoration: none;
            font-weight: 500;
        }

        @media (max-width: 768px) {
            .login-image {
                display: none;
            }

            .login-content {
                min-width: 100%;
            }
        }

        /* 添加加载动画样式 */
        .loading-overlay {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(255, 255, 255, 0.9);
            display: none;
            justify-content: center;
            align-items: center;
            z-index: 1000;
        }

        .loading-overlay.show {
            display: flex;
        }

        .loading-spinner {
            width: 50px;
            height: 50px;
            border: 3px solid #f3f3f3;
            border-top: 3px solid #4776E6;
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }

        .loading-text {
            position: absolute;
            margin-top: 80px;
            color: #4776E6;
            font-size: 16px;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
    </style>
</head>
<body>
<div id="announcement-bar" class="alert-bar" style="position: fixed; top: 0; left: 0; right: 0; background-color: #ffcc00; color: #333; padding: 12px; text-align: center; font-size: 14px; z-index: 1000; box-shadow: 0 2px 4px rgba(0,0,0,0.1); white-space: nowrap; overflow-x: auto; -webkit-overflow-scrolling: touch;">
</div>
<div class="login-container">
    <div class="login-card">
        <div class="login-image">
            <img src="assets/images/bg.svg" alt="登录插图">
            <h2>欢迎使用Cursor Task</h2>
            <p>这是一个安全、高效、易用的管理系统，助力您的业务发展。</p>
        </div>

        <div class="login-content">
            <div class="login-header">
                <h1>欢迎登录</h1>
                <p>请使用您的账号密码登录系统</p>
            </div>

            <div class="login-form">
                <form>
                    <div class="form-group">
                        <label class="form-label">用户名</label>
                        <input type="text" class="form-input" placeholder="请输入用户名">
                    </div>

                    <div class="form-group">
                        <label class="form-label">密码</label>
                        <input type="password" class="form-input" placeholder="请输入密码">
                    </div>

                    <div class="form-footer">
                        <label class="remember-me">
                            <input type="checkbox">
                            <span>记住我</span>
                        </label>
                        <a href="#" class="forgot-password">忘记密码？</a>
                    </div>

                    <button type="submit" class="login-button">登录</button>

                    <div class="login-divider">
                        <span>其他登录方式</span>
                    </div>

                    <div class="social-login">
                        <button type="button" class="social-button" disabled style="opacity: 0.6; cursor: not-allowed;">
                            <svg width="20" height="20" viewBox="0 0 24 24" fill="#2d3436">
                                <path d="M12 2C6.477 2 2 6.477 2 12c0 4.42 2.865 8.164 6.839 9.49.5.09.682-.217.682-.482 0-.237-.008-.866-.013-1.7-2.782.603-3.369-1.34-3.369-1.34-.454-1.156-1.11-1.462-1.11-1.462-.908-.62.069-.608.069-.608 1.003.07 1.531 1.03 1.531 1.03.892 1.529 2.341 1.087 2.91.831.092-.646.35-1.086.636-1.336-2.22-.253-4.555-1.11-4.555-4.943 0-1.091.39-1.984 1.029-2.683-.103-.253-.446-1.27.098-2.647 0 0 .84-.269 2.75 1.025A9.578 9.578 0 0112 6.836c.85.004 1.705.114 2.504.336 1.909-1.294 2.747-1.025 2.747-1.025.546 1.377.203 2.394.1 2.647.64.699 1.028 1.592 1.028 2.683 0 3.842-2.339 4.687-4.566 4.935.359.309.678.919.678 1.852 0 1.336-.012 2.415-.012 2.743 0 .267.18.577.688.48C19.138 20.161 22 16.418 22 12c0-5.523-4.477-10-10-10z"/>
                            </svg>
                            暂未对接
                        </button>
                        <button type="button" class="social-button" disabled style="opacity: 0.6; cursor: not-allowed;">
                            <svg width="20" height="20" viewBox="0 0 24 24" fill="#2d3436">
                                <path d="M12 2C6.477 2 2 6.477 2 12c0 4.991 3.657 9.128 8.438 9.879V14.89h-2.54V12h2.54V9.797c0-2.506 1.492-3.89 3.777-3.89 1.094 0 2.238.195 2.238.195v2.46h-1.26c-1.243 0-1.63.771-1.63 1.562V12h2.773l-.443 2.89h-2.33v6.989C18.343 21.129 22 16.99 22 12c0-5.523-4.477-10-10-10z"/>
                            </svg>
                            暂未对接
                        </button>
                    </div>
                </form>
            </div>

            <div class="register-link">
                还没有账号？ <a href="/register">立即注册</a>
            </div>
        </div>
    </div>
</div>

<!-- 添加加载动画HTML -->
<div class="loading-overlay">
    <div class="loading-spinner"></div>
    <div class="loading-text">正在进入系统...</div>
</div>

<!-- 添加更新对话框HTML -->
<div class="dialog-overlay force-update"></div>
<div class="update-dialog force-update">
    <h3>系统更新</h3>
    <div class="update-info"></div>
    <div class="update-notice">
        <i class="fas fa-exclamation-circle"></i>
        <span>检测到重要更新，请立即更新后继续使用</span>
    </div>
    <div class="update-actions">
        <button class="update-button update-now">
            <i class="fas fa-download"></i>
            立即更新
        </button>
    </div>
</div>

<script>
    // 在现有脚本的开头添加获取公告的函数
    async function fetchAnnouncement() {
        try {
            const response = await fetch(`${BASE_URL}/api/announcement/3`, {
                headers: {
                    'accept': 'application/json'
                }
            });
            const result = await response.json();
            
            if (result.code === 200 && result.data.is_active) {
                const announcementBar = document.getElementById('announcement-bar');
                // 显示标题和内容
                announcementBar.innerHTML = `<span style="font-weight: bold;">${result.data.title}</span>: ${result.data.content}`;
                announcementBar.style.display = 'block';
            }
        } catch (error) {
            console.error('获取公告失败:', error);
        }
    }

    // 页面加载时获取公告
    window.addEventListener('load', fetchAnnouncement);

    // 登录表单提交处理
    document.querySelector('.login-form form').addEventListener('submit', async function (e) {
        e.preventDefault(); // 阻止表单默认提交行为

        // 获取表单数据
        const username = document.querySelector('input[type="text"]').value;
        const password = document.querySelector('input[type="password"]').value;

        // 表单验证
        if (!username || !password) {
            showMessage('用户名和密码不能为空', 'error');
            return;
        }

        try {
            // 显示加载状态
            const loginButton = document.querySelector('.login-button');
            const originalText = loginButton.textContent;
            loginButton.disabled = true;
            loginButton.textContent = '登录中...';

            console.log('尝试登录:', { username });  // 添加日志，不输出密码
            
            // 使用 API 封装的登录方法
            const loginResult = await API.login(username, password);
            console.log('登录成功，结果:', loginResult);  // 添加日志
            
            // 处理"记住我"功能
            const rememberMeCheckbox = document.querySelector('.remember-me input');
            if (rememberMeCheckbox.checked) {
                localStorage.setItem('remembered_username', username);
            } else {
                localStorage.removeItem('remembered_username');
            }
            
            // 登录成功后立即加载用户资料
            await API.loadInitialData();
            
            showMessage('登录成功', 'success');

            // 显示加载动画
            document.querySelector('.loading-overlay').classList.add('show');

            try {
                console.log('开始获取用户信息...');
                // 获取用户信息
                const userInfo = await API.getUserInfo();
                console.log('获取用户信息成功:', userInfo);
                
                // 先设置一个标记，表示是从登录页面来的
                sessionStorage.setItem('from_login', 'true');
                setTimeout(() => {
                    window.location.href = '/main';
                }, 1500);
            } catch (error) {
                console.error('加载用户信息失败:', error);
                document.querySelector('.loading-overlay').classList.remove('show');
                showMessage(error.message || '系统初始化失败，请重试', 'error');
                // 清除token和状态
                localStorage.removeItem('access_token');
                if (window.AppState) {
                    AppState.clear();
                }
            }
        } catch (error) {
            console.error('登录失败，完整错误:', error);  // 添加更详细的错误日志
            
            // 处理登录错误
            if (error.code === 422) {
                showMessage('用户名或密码错误', 'error');
            } else {
                showMessage(error.message || '登录失败，请重试', 'error');
            }
        } finally {
            // 恢复按钮状态
            const loginButton = document.querySelector('.login-button');
            loginButton.disabled = false;
            loginButton.textContent = '登录';
        }
    });

    // 消息提示功能
    function showMessage(message, type = 'info') {
        // 如果已存在消息框，先移除
        const existingMessage = document.querySelector('.message-box');
        if (existingMessage) {
            existingMessage.remove();
        }

        // 创建消息框
        const messageBox = document.createElement('div');
        messageBox.className = `message-box message-${type}`;
        messageBox.textContent = message;

        // 添加样式
        Object.assign(messageBox.style, {
            position: 'fixed',
            top: '20px',
            left: '50%',
            transform: 'translateX(-50%)',
            padding: '12px 24px',
            borderRadius: '8px',
            backgroundColor: type === 'success' ? '#10b981' : '#ef4444',
            color: 'white',
            fontSize: '14px',
            boxShadow: '0 4px 12px rgba(0, 0, 0, 0.15)',
            zIndex: '1000',
            transition: 'all 0.3s ease'
        });

        document.body.appendChild(messageBox);

        // 3秒后自动消失
        setTimeout(() => {
            messageBox.style.opacity = '0';
            setTimeout(() => messageBox.remove(), 300);
        }, 3000);
    }

    // 记住我功能
    const rememberMeCheckbox = document.querySelector('.remember-me input');
    const usernameInput = document.querySelector('input[type="text"]');

    // 页面加载时检查是否有保存的用户名
    window.addEventListener('load', () => {
        const savedUsername = localStorage.getItem('remembered_username');
        if (savedUsername) {
            usernameInput.value = savedUsername;
            rememberMeCheckbox.checked = true;
        }
    });

    // 记住用户名
    rememberMeCheckbox.addEventListener('change', () => {
        if (rememberMeCheckbox.checked) {
            localStorage.setItem('remembered_username', usernameInput.value);
        } else {
            localStorage.removeItem('remembered_username');
        }
    });

    // 用户名输入变化时更新存储
    usernameInput.addEventListener('input', () => {
        if (rememberMeCheckbox.checked) {
            localStorage.setItem('remembered_username', usernameInput.value);
        }
    });

    // 检查更新功能
    async function checkUpdate() {
        try {
            const loadingMessage = showMessage('正在检查更新...', 'info', true);
            const response = await fetch('https://autotask.top/api/app/check-update', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    app_name: 'CursorTask',
                    current_version: '0.0.1'
                })
            });

            const result = await response.json();
            if (loadingMessage && loadingMessage.parentNode) {
                loadingMessage.parentNode.removeChild(loadingMessage);
            }

            if (result.code === 200) {
                if (result.msg === '当前已是最新版本') {
                    showMessage(result.msg, 'success');
                } else {
                    const {version, update_info, download_url} = result.data;
                    showUpdateDialog(version, update_info, download_url);
                    // 默认禁用所有导航链接
                    disableNavigation();
                }
            } else {
                throw new Error(result.msg || '检查更新失败');
            }
        } catch (error) {
            console.error('检查更新失败:', error);
            showMessage(error.message, 'error');
        }
    }

    // 显示更新对话框函数
    function showUpdateDialog(version, updateInfo, downloadUrl) {
        const dialog = document.querySelector('.update-dialog');
        const overlay = document.querySelector('.dialog-overlay');
        const updateInfoElement = dialog.querySelector('.update-info');

        updateInfoElement.innerHTML = `
            <p><strong>最新版本：</strong>${version}</p>
            <p><strong>更新内容：</strong></p>
            <p>${updateInfo}</p>
        `;

        // 默认添加强制更新类
        dialog.classList.add('force-update', 'show');
        overlay.classList.add('force-update', 'show');
        
        // 禁用ESC键关闭
        document.addEventListener('keydown', preventEscapeKey);

        // 绑定按钮事件
        const updateNowButton = dialog.querySelector('.update-now');
        updateNowButton.onclick = () => {
            // 检查是否在 pywebview 环境中
            if (window.pywebview !== undefined) {
                // 使用 pywebview API 打开链接
                window.pywebview.api.openExternal(downloadUrl);
            } else {
                // 在普通浏览器环境中使用 window.open
                window.open(downloadUrl, '_blank');
            }
            // 强制更新不关闭对话框
        };
    }

    // 禁用导航功能
    function disableNavigation() {
        // 禁用登录表单
        document.querySelectorAll('input, button').forEach(element => {
            if (!element.closest('.update-dialog')) {
                element.disabled = true;
                element.style.opacity = '0.5';
                element.style.cursor = 'not-allowed';
            }
        });

        // 禁用所有链接
        document.querySelectorAll('a').forEach(link => {
            link.style.pointerEvents = 'none';
            link.style.opacity = '0.5';
            link.style.cursor = 'not-allowed';
        });
    }

    // 阻止ESC键关闭对话框
    function preventEscapeKey(e) {
        if (e.key === 'Escape') {
            e.preventDefault();
            showMessage('请先完成更新后继续使用', 'error');
        }
    }

    // 页面加载完成后执行检查更新
    document.addEventListener('DOMContentLoaded', function() {
        setTimeout(checkUpdate, 1000);
    });
</script>
</body>
</html>
